import Vue from 'vue'
import VueRouter from 'vue-router'
import MyIndex from '../views/MyIndex.vue'
import Index from "../views/Index";
import Detail from '../views/Detail';
import Mine from '../views/Mine';
import Vuex from '../views/Vuex'
import {getUserInfo} from "../api/api";

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/myIndex/index'
  },
  {
    path: '/vuex',
    component: Vuex
  },
  {
    path: '/myIndex',
    name: 'MyIndex',
    component: MyIndex,
    children:[
      {
        path:'detail',
        component:Detail
      },
      {
        path:'index',
        component:Index
      },
      {
        path:'mine',
        component:Mine,
        //需要登录
        meta:{
          needLogin:true
        }
      },

    ]
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  // ...
  // console.log(this.$store.state.isLogin)
  console.log(to)
  // console.log(from)
  console.log(next)
  //如果需要登录
  if(to.meta.needLogin){
    //确认登录状态
    getUserInfo().then(res => {
      if(res.data.code == 0){
        //如果登录放行
        next()
      }else{
        //如果没登录返回首页
        next('/')
        alert('请先登录')
      }
    })
  //  如果不需要登录直接放行
  }else{
    next()
  }

})
export default router
